<template>
  <div id="container">
    <div class="content">
      <div class="icon">
        <img src="/src/assets/images/startpoint.png" style="width: 35px" />
      </div>
      <div class="lng">
        <div class="title">经度：</div>
        <div class="text">{{ pointInfo.lng }}</div>
      </div>
      <div class="lng">
        <div class="title">纬度：</div>
        <div class="text">{{ pointInfo.lat }}</div>
      </div>
      <div class="address">
        <div class="title">详细地址：</div>
        <div class="text">{{ pointInfo.address }}</div>
      </div>
      <div class="allbtn">
        <el-button class="btn" @click="removemarker">删除</el-button>
        <el-button class="btn" type="primary" @click="handlermarker"
          >确定</el-button
        >
      </div>
    </div>
    <!--  地址搜索  -->
    <div id="myPageTop">
      <input
        id="tipinput"
        @focus="clearDetele = true"
        @keydown.enter="mapSelect"
        placeholder="请输入地址"
      />
      <img
        v-if="clearDetele"
        src="@/assets/images/close.png"
        class="deleteClearBle"
        @click="clearableHandle"
        alt=""
      />
      <el-button @click="mapSelect"> 搜索 </el-button>
    </div>
  </div>
</template>

<script setup>
// import { getProvinceApi } from "@/api/information/customer";
import { getAreaList } from "@/api/dict";
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({
  // 操作类型
  projectForm: {
    type: Object,
    default: {},
  },
  // 页面状态
  pagestatus: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["handlerselect"]);
const clearDetele = ref(false);
let aMap = null;

// 省列表
let provinceList = ref([]);
// 市列表
let cityList = ref([]);

// 区列表
let areaList = ref([]);
// 街道列表
let streetList = ref([]);

/**
 * @设置高德地图地理编码城市为杭州
 * */
let geocoder = new AMap.Geocoder({
  // city: "330100", //城市设为杭州，默认：“全国”
});
// 当前绘制的航点信息集合
const pointInfo = reactive({
  lng: "",
  lat: "",
  address: "",
});
// 点击地图绘制的临时航点 marker
let tempMarker = null;
let auto = ref(null);
let placeSearch = ref(null);

const initMap = () => {
  aMap = new AMap.Map("container", {
    // viewMode: "3D",
    zoom: 12,
    center: [120.209947, 30.245853],
    // mapStyle: "amap://styles/fresh",
    resizeEnable: true,
    lang: "en", //可选值：en，zh_en, zh_cn
  });

  //输入提示
  var autoOptions = {
    input: "tipinput",
  };
  AMap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], function () {
    var auto = new AMap.AutoComplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
      map: aMap,
    }); //构造地点查询类
    auto.on("select", select); //注册监听，当选中某条记录时会触发
    function select(e) {
      placeSearch.setCity(e.poi.adcode);
      placeSearch.search(e.poi.name); //关键字查询查询
    }
  });
};

function select(e) {
  placeSearch.setCity(e.poi.adcode);
  placeSearch.search(e.poi.name); //关键字查询查询
}
/**
 * @开始绘制航线 : 地图添加单击获取经纬度
 * */
function startDrawLine() {
  // 获取地图上点击的经纬度
  aMap.on("click", clickMap);
}

/**
 * @地图点击事件 : 获取经纬度，绘制临时marker
 * */
function clickMap(e) {
  // 绘制临时航点的 marker
  pointInfo.lng = e.lnglat.lng;
  pointInfo.lat = e.lnglat.lat;
  if (tempMarker) aMap.remove(tempMarker);
  tempMarker = drawMarker({ ...pointInfo });
  aMap.add(tempMarker);
}

/**
 * @地图绘制marker点
 * @content 航点信息
 * @callback 航点点击回调事件
 * */
const drawMarker = (content) => {
  let marker = new AMap.Marker({
    position: [content.lng, content.lat],
    // icon: new AMap.Icon({
    //   size: new AMap.Size(40, 40), // 图标尺寸
    //   image: `@/assets/images/startpoint.png`,
    //   imageSize: new AMap.Size(40, 40),
    // }),
    content: `<div class="unattended"></div>`,
    offset: new AMap.Pixel(-20, -35),
    bubble: true,
  });
  geocoder.getAddress([content.lng, content.lat], (status, result) => {
    pointInfo.address = result.regeocode.formattedAddress;
  });
  marker.content = content;
  return marker;
};
/**
 * @地图回显marker点
 * */
const EchoMarker = (content) => {
  let marker = new AMap.Marker({
    position: [content.lng, content.lat],
    // icon: new AMap.Icon({
    //   size: new AMap.Size(40, 40), // 图标尺寸
    //   image: `@/assets/images/startpoint.png`,
    //   imageSize: new AMap.Size(40, 40),
    // }),
    content: `<div class="unattended"></div>`,
    offset: new AMap.Pixel(-20, -35),
    bubble: true,
  });
  aMap.add(marker);
  aMap.setFitView(marker);
};

let marker = new AMap.Marker();
const mapSelect = () => {
  let inputValue = document.getElementById("tipinput");
  if (!inputValue.value) {
    ElMessage.warning("请输入地址"); // 请输入地址！
    var mybounds = new AMap.Bounds(
      [120.04403, 30.080745],
      [120.371217, 30.345388]
    );
    aMap.setBounds(mybounds);
    // aMap.clearMap();
    aMap.remove(marker);
  } else {
    geocoder.getLocation(inputValue.value, function (status, result) {
      if (status === "complete" && result.geocodes.length) {
        var lnglat = result.geocodes[0].location;
        console.log(lnglat);
        // document.getElementById('lnglat').value = lnglat;
        marker.setPosition(lnglat);
        aMap.add(marker);
        aMap.setFitView(marker);
      } else {
        log.error("根据地址查询位置失败");
      }
    });
    // placeSearch.setCity(dataPoi.adcode);
    // placeSearch.search(dataPoi.name); //关键字查询查询
  }
};
const removemarker = () => {
  aMap.remove(tempMarker);
  pointInfo.lng = "";
  pointInfo.lat = "";
  pointInfo.address = "";
};
/**
 * @清除pio搜索
 * */
const clearableHandle = () => {
  document.getElementById("tipinput").value = "";
  clearDetele.value = false;
};

/**
 * @完成绘制航线 : 移除地图点击事件
 * */
function finishDraw() {
  aMap.off("click", clickMap);
  pointInfo.lng = null;
  pointInfo.lat = null;
  pointInfo.height = null;
}

const handlermarker = () => {
  if (pointInfo.lng != "") {
    emit("handlerselect", pointInfo);
  } else {
    ElMessage.error("请选择详细地址");
  }
};
/**
 * @处理地址反查
 * */
const handleraddress = (address) => {
  geocoder.getLocation(address, function (status, result) {
    if (status === "complete" && result.geocodes.length) {
      var lnglat = result.geocodes[0].location;
      console.log("lnglat", lnglat);
      aMap.setZoomAndCenter(11, [lnglat.lng, lnglat.lat], false, 1000);
    } else {
      // log.error("根据地址查询位置失败");
    }
  });
};

/**
 * @处理编辑回显
 * */
const handleredit = () => {
  console.log("(props.projectForm", props.projectForm);
  pointInfo.address = props.projectForm.address;
  pointInfo.lng = props.projectForm.longitude;
  pointInfo.lat = props.projectForm.latitude;
  EchoMarker({ ...pointInfo });
};

onMounted(() => {
  initMap();
  startDrawLine();
  if (props.pagestatus == "edit") {
    handleredit();
  }
  // console.log("(props.projectForm", props.projectForm);
  // if (props.projectForm.provinceId) {
  //   let str = "";
  //   getAreaList({ pid: 1 }).then((res) => {
  //     console.log("res", res);
  //     if (res.code === 200) {
  //       provinceList.value = res.data;

  //       let aa = provinceList.value.find((item, index) => {
  //         if (props.projectForm.provinceId == item.value) {
  //           return item;
  //         }
  //       });
  //       str = str + aa.label;

  //       getAreaList({ pid: props.projectForm.provinceId }).then((res) => {
  //         if (res.code === 200) {
  //           cityList.value = res.data;
  //           let bb = cityList.value.find((jtem, index) => {
  //             if (props.projectForm.cityId == jtem.value) {
  //               return jtem;
  //             }
  //           });

  //           str = str + bb.label;
  //           getAreaList({ pid: props.projectForm.cityId }).then((res) => {
  //             if (res.code === 200) {
  //               areaList.value = res.data;
  //               let cc = areaList.value.find((ctem, index) => {
  //                 if (props.projectForm.zoneId == ctem.value) {
  //                   return ctem;
  //                 }
  //               });
  //               str = str + cc.label;
  //               getAreaList({ pid: props.projectForm.zoneId }).then((res) => {
  //                 if (res.code == 200) {
  //                   streetList.value = res.data;
  //                   let dd = streetList.value.find((dtem, index) => {
  //                     if (props.projectForm.zoneId == dtem.value) {
  //                       return dtem;
  //                     }
  //                   });
  //                   str = str + dd.label;
  //                   console.log("str", str);
  //                   handleraddress(str);
  //                 }
  //               });
  //             }
  //           });
  //         }
  //       });
  //     }
  //   });
  // }
});
/**
 * @挂载生命周期
 * */
/**
 * @组件销毁时销毁地图
 * */
onUnmounted(() => {
  finishDraw();
  aMap.destroy();
});
</script>

<style scoped lang="scss">
#container {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 0;
  .content {
    display: flex;
    position: absolute;
    bottom: 0;
    left: 0;
    background-color: #f0f0f0;
    z-index: 1;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    border-radius: 5px 0;
    padding: 0 20px;
    .lng,
    .address,
    .allbtn {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
#myPageTop {
  width: 370px;
  height: 40px;
  top: 36px;
  right: 40px;
  position: absolute;
  display: flex;
  z-index: 1;

  .deleteClearBle {
    width: 11px;
    height: 11px;
    position: relative;
    top: 15px;
    right: 40px;
    cursor: pointer;
  }

  input {
    width: 270px;
    height: 40px;
    opacity: 1;
    margin-right: 20px;
    padding: 0 10px;
    border-radius: 4px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(220, 223, 230, 1);
  }

  .el-button {
    width: 80px;
    height: 40px;
    opacity: 1;
    border-radius: 4px;
    background: rgba(43, 193, 123, 1);
    color: #ffffff;
  }
}
:deep(.amap-logo) {
  /* //去掉高德地图logo */
  display: none !important;
}
:deep(.l7-marker-container) {
  display: none;
}
:deep(.amap-copyright) {
  /* //去掉高德的版本号 */
  opacity: 0 !important;
  z-index: -1;
}
/* // 地图加载时 闪白屏问题 */
:deep(.amap-container) {
  background-color: transparent !important;
}
</style>

<style>
.unattended {
  width: 40px;
  height: 40px;
  background: url("@/assets/images/startpoint.png") no-repeat;
  background-size: 100% 100%;
}
</style>
